<?php
/**
 *
 * Author: Lyu
 * Date: 2023/7/22
 * Time: 15:13
 */

namespace App\Model\Core\Admin;

use App\Model\CoreModel;

class AdminMenuModel extends CoreModel
{
    protected string $table = 'admin_menu';

    /**
     * 获取单条信息
     * @param int $id
     * @param bool $is_cache
     * @return array
     */
    public function getOne(int $id, bool $is_cache = true): array
    {
        if ($id <= 0) {
            return [];
        }
        return $this->cache($id, function () use ($id) {
            return obj_to_array($this->getConnectionTable()->where('id', $id)->first());
        }, $is_cache);
    }

    public function getAllMenu($is_cache = true): array
    {
        return $this->cache('list', function () {
            return obj_to_array($this->getConnectionTable()->orderBy('sort_order')->orderBy('id')->get());
        }, $is_cache);
    }

    public function getMenuByIds(array $ids): array
    {
        if (empty($ids)) {
            return [];
        }
        return obj_to_array($this->getConnectionTable()
            ->whereIn('id', $ids)
            ->orderBy('sort_order')
            ->orderBy('id')
            ->get());
    }

    public function getSubMenuList($parent_id, $sort = 'asc'): array
    {
        return obj_to_array($this->getConnectionTable()
            ->where('parent_id', $parent_id)
            ->orderBy('sort_order', $sort)
            ->orderBy('id')
            ->get());
    }

    /**
     * 添加用户信息
     * @param array $data
     * @return bool|int
     */
    public function addOne(array $data): int|bool
    {
        if (empty($data)) {
            return false;
        }
        return $this->getConnectionTable()->insertGetId($data);
    }

    /**
     * 更新用户信息
     * @param int $id
     * @param array $data
     * @return bool
     */
    public function updateOne(int $id, array $data): bool
    {
        if ($id <= 0 || empty($data)) {
            return false;
        }
        $old_info = self::getOne($id);
        $res = $this->getConnectionTable()->where('id', $id)->update($data);
        if ($res) {
            self::clearCache($old_info);
        }
        return $res;
    }


    /**
     * 删除用户信息
     * @param int $id
     * @return bool
     */
    public function deleteOne(int $id): bool
    {
        if ($id <= 0) {
            return false;
        }
        $old_info = self::getOne($id);
        if (empty($old_info)) {
            return false;
        }
        $res = $this->getConnectionTable()->where('id', $id)->delete();
        if ($res) {
            self::clearCache($old_info);
        }
        return $res;
    }

    /**
     * 清空缓存
     * @param array $old_info
     * @return $this
     */
    public function clearCache(array $old_info): self
    {
        $cache_k = $old_info['id'];
        $this->cleanCache($cache_k);
        $cache_k = 'list';
        $this->cleanCache($cache_k);
        return $this;
    }
}
